package com.wenhai.leetcode.set;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 *https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
 *
 * @author wenhai
 * @date   2021/3/8
 */
public class _350两个数组的交集II {
    public int[] intersect(int[] nums1, int[] nums2) {
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        List<Integer> list = new ArrayList<>();
        for (int num : nums1) {
            treeMap.merge(num, 1, (o, n) -> o + n);
        }
        for (int num : nums2) {
            if (treeMap.containsKey(num)) {
                list.add(num);
                treeMap.computeIfPresent(num, (k, v) -> {
                    if (--v > 0) {
                        return v;
                    }
                    return null;
                });
            }
        }
        int[] resultArr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            resultArr[i] = list.get(i);
        }
        return resultArr;

    }
}
